package com.example.aijie.autoreadhelper.utils;

import com.example.aijie.autoreadhelper.service.AutoReadService;

import java.io.DataOutputStream;
import java.io.OutputStream;
import java.util.Random;

public class RoomUtils {
    /**
     * 点击
     */
    public static void performClick() {
        execShellCmd("input tap 500 500");
    }

    /**
     * 列表向下滚动
     */
    public static void performListScrollDown() {
        if (AutoReadService.appBean != null) {
            int itemHeight = AutoReadService.appBean.getItemHeight();
            if (itemHeight <= 0) {
                itemHeight = 400;
            }
            execShellCmd("input swipe 500 1200 500 ".concat(String.valueOf(1200 - itemHeight)));
        } else {
            execShellCmd("input swipe 500 1200 500 800");
        }
    }

    /**
     * 文章向下滚动
     */
    public static void performArticleScrollDown() {
        int randomInt = new Random().nextInt(100);
        execShellCmd("input swipe 500 1200 500 ".concat(String.valueOf(1100 - randomInt)));
    }

    /**
     * 列表向上滚动
     */
    public static void performListScrollUp() {
        execShellCmd("input swipe 500 600 500 1000");
    }

    /**
     * 文章向上滚动
     */
    public static void performArticleScrollUp() {
        execShellCmd("input swipe 500 600 500 1000");
    }

    /**
     * 手机点击返回按键
     */
    public static void performBack() {
        execShellCmd("input keyevent 4");
    }

    /**
     * 执行shell命令
     *
     * @param cmd
     */
    private static void execShellCmd(String cmd) {

        try {
            // 申请获取root权限，这一步很重要，不然会没有作用
            Process process = Runtime.getRuntime().exec("su");
            // 获取输出流
            OutputStream outputStream = process.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(
                    outputStream);
            dataOutputStream.writeBytes(cmd);
            dataOutputStream.flush();
            dataOutputStream.close();
            outputStream.close();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

}
